package com.springcloud.controller;

import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.EurekaClient;
import com.springcloud.pojo.Address;
import com.springcloud.pojo.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Random;

/**
 * @Author 咕唧
 * @Date 2022/6/23 17:07
 * @Version 1.0
 */
@RestController
@RequestMapping("/order")
public class OrderController {

    private Random random = new Random();

    private RestTemplate restTemplate;

    private EurekaClient eurekaClient;

    @Autowired
    public void setEurekaClient(EurekaClient eurekaClient) {
        this.eurekaClient = eurekaClient;
    }

    @Autowired
    public void setRestTemplate(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    @GetMapping("/info/{id}")
    public Order findById(@PathVariable Long id) {
        Order order = new Order();
        order.setItemName("订单名字-----" + random.nextInt());
        order.setId(id);
        order.setPrice(random.nextDouble());

        //实体类地址中的数据不在当前程序内部,在另外一个服务器的程序里面
        //通过访问其他项目http接口，拿到需要的数据
        //现在我们的地址都在注册中心中,所以我们需要从里面获取,参数1 就是我们想要的功能在eureka中的名字,参数2 是不是https
        InstanceInfo instanceInfo = eurekaClient.getNextServerFromEureka("04ADDRESSPROVIDER", false);
        //获取拿到的服务器地址信息,到端口
        String homePageUrl = instanceInfo.getHomePageUrl();
//        System.err.println(homePageUrl);

        Address address = restTemplate.getForObject(homePageUrl+"/address/info/" + id, Address.class);
        order.setAddress(address);

        return order;
    }
}
